package thread;

import java.util.concurrent.atomic.AtomicInteger;

public class test22 {
    // AtomicInteger可以将++或--操作封装成原子操作
    // 防止在多线程下针对同一个变量出现线程不安全问题，由于以下代码不涉及加锁操作，所以执行的效率更高
    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        // 实现原子类：
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                // count++
                count.getAndIncrement();
                // ++count
                count.incrementAndGet();
                // count--
                count.getAndDecrement();
                // --count
                count.decrementAndGet();
                // count += 10
                count.getAndAdd(10);
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count.getAndIncrement();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}
